﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using FinancePortal.Business.Repository;
using FinancePortal.Web.Model;
using FinancePortal.Domain.Enum;

namespace FinancePortal.Web.Controllers
{
    public class AccountController : Controller
    {
        private readonly IResourceRepository _resourceRepository;
        private readonly IAreaRepository _areaRepository;

        public AccountController(IResourceRepository resourceRepository,
            IAreaRepository areaRepository)
        {
            _resourceRepository = resourceRepository;
            _areaRepository = areaRepository;
        }

        public ActionResult LogOn()
        {
            var text = base.Request["ReturnUrl"];
            var soeid = ResourceManagement.GetSOEID(this.Request);

            if (Membership.Provider.ValidateUser(soeid, String.Empty))
            {
                ActionResult result;
                FormsAuthentication.SetAuthCookie(soeid, false);
                var resource = _resourceRepository.GetBySOEID(soeid);
                Session["UserName"] = resource.Name;
                Session["IsAdmin"] = resource.Profile == (int)Profile.Administrator;

                if (!string.IsNullOrEmpty(text))
                {
                    result = this.Redirect(text);
                }
                else
                {
                    result = base.RedirectToAction("Index", "Home");
                }

                return result;
            }
            else
            {
                return RedirectToAction("UnAuthorized", "Error");
            }
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("UnAuthorized", "Error");
        }
    }
}
